package com.yamibuy.ec.resource.handler;

import cn.hutool.core.io.IoUtil;
import com.yamibuy.ec.resource.aws.AwsS3Util;
import com.yamibuy.ec.resource.aws.AwsUrlDecode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletResponse;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

/**
 * 图片处理
 *
 * @author: damon.li
 * @version: 2021年02月23日 8:33
 */
@Component
@Slf4j
public class FileHandler implements RequestHandlerFlag<String> {

	/**
	 * 需要处理的文件格式， 取反逻辑则为所有文件
	 */
	private static final String handleImagePathReg = "(^(/\\w+)+/\\w{32}_(.+)\\.(jpg|png|webp|tiff|jpeg|bmp|gif|GIF)$)|(^(/\\w+)+/\\w{32}\\.?(jpg|png|webp|tiff|jpeg|bmp|gif|GIF)?$)|(^(/\\w+).+\\.(jpg|png|webp|tiff|jpeg|bmp|gif|GIF)$)";

	@Resource
	private AwsS3Util awsS3Util;

	@Override
	public ByteArrayOutputStream handle(String requestKeyRule) throws Exception {
		log.debug("收到文件求: {} ", requestKeyRule);
		// 文件直接截取路径
		requestKeyRule = requestKeyRule.substring(1, requestKeyRule.length());
		requestKeyRule = AwsUrlDecode.decode(requestKeyRule);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] file = awsS3Util.getFile(requestKeyRule);
		IoUtil.write(out, true, file);
		return out;
	}

	@Override
	public boolean flag(String path) {
		boolean matches = !path.matches(handleImagePathReg);
		return matches;
	}

	@Override
	public RequestHandlerFlag responseHeader(ServletResponse servletResponse) {
		servletResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
		servletResponse.setCharacterEncoding(Charset.defaultCharset().name());
		return this;
	}
}
